using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Domain.CircleServe.Entity.dto;
using imitateMacQQ.WebApi.Domain.CircleServe.Interface;
using imitateMacQQ.WebApi.Domain.Request.utils;
using imitateMacQQ.WebApi.Repository.EFCore.Model;
using imitateMacQQ.WebApi.Repository.EFCore.Model.Circle;
using Microsoft.EntityFrameworkCore;

namespace imitateMacQQ.WebApi.Domain.CircleServe.Service;

public class ReleaseService : IReleaseInfo
{
    private readonly INLogHelper _logHelper;

    public ReleaseService(INLogHelper log)
    {
        _logHelper = log;
    }

    [Obsolete("Obsolete")]
    public async Task<Request<bool>> Release(IFormFileCollection? files, ReleaseInfo dto)
    {
        string pathSql = String.Empty;
        try
        {
            if (files?.Count > 0)
            {
                var webRootPath = Path.Combine(Directory.GetCurrentDirectory(),
                    "StaticFiles/") + dto.SendAccount + "/" + "Circle" + "/";
                foreach (var formFile in files)
                {
                    if (formFile.Length <= 0) continue;
                    var fileExt = Guid.NewGuid().ToString().Replace("-", "0") + "." + formFile.FileName.Split('.')[1];
                    Directory.CreateDirectory(webRootPath);
                    var filePath = webRootPath + fileExt;
                    await using var stream = new FileStream(filePath, FileMode.Create);
                    await formFile.CopyToAsync(stream);
                    pathSql += dto.SendAccount + "/" + "Circle" + "/" + fileExt + "-";
                }
            }

            await using var db = new DataDbContext();
            await db.FriendCircles.AddAsync(new FriendCircle()
            {
                SendTime = DateTime.Now,
                SendAccount = dto.SendAccount,
                Content = dto.Content,
                LikeSum = 0,
                IsShow = dto.IsShow,
                HasPrintPicture = pathSql.Length > 1,
                PrintPicture = pathSql,
                Remarks = CreateOrderNo()
            });
            await db.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
            return Request<bool>.Ok(false, false, ex.Message);
        }

        return Request<bool>.Ok(true);
    }

    public async Task<Request<bool>> Del(string remarks)
    {
        try
        {
            await using DataDbContext db = new DataDbContext();
            var info = await db.FriendCircles.FirstOrDefaultAsync(e =>
                e.Remarks == remarks);
            if (info is null)
                throw new Exception("DATA IS NULL!---FRIEND_CIRCLE");
            db.FriendCircles.Remove(info);
            await db.SaveChangesAsync();
            return Request<bool>.Ok(true);
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
        }

        return Request<bool>.Ok(false, false, "NOT ON LIVE");
    }


    //UUID生成

    [Obsolete("Obsolete")]
    private static string CreateOrderNo()
    {
        var strNo = DateTime.Now.ToString("yyMMddHHmmssmm");
        var iSeed = CreateRandSeed();
        var iSeed2 = NextRandom(1000, 2);
        iSeed = iSeed - 500 + iSeed2;
        var rnd = new Random(iSeed);
        var strExt = rnd.Next(1000, 10000);
        strNo += strExt;

        //再拼接2位
        rnd = new Random(iSeed - 1);
        strExt = rnd.Next(10, 99);
        strNo += strExt;
        return strNo;
    }

    [Obsolete("Obsolete")]
    private static int NextRandom(int numSeeds, int length)
    {
        // Create a byte array to hold the random value.    
        byte[] randomNumber = new byte[length];
        // Create a new instance of the RNGCryptoServiceProvider.    
        System.Security.Cryptography.RNGCryptoServiceProvider rng =
            new System.Security.Cryptography.RNGCryptoServiceProvider();
        // Fill the array with a random value.    
        rng.GetBytes(randomNumber);
        // Convert the byte to an uint value to make the modulus operation easier.    
        uint randomResult = 0x0;
        for (int i = 0; i < length; i++)
        {
            randomResult |= ((uint)randomNumber[i] << ((length - 1 - i) * 8));
        }

        return (int)(randomResult % numSeeds) + 1;
    }

    private static int CreateRandSeed()
    {
        var guid = Guid.NewGuid().ToString();
        var iSeed = guid.GetHashCode();
        return iSeed;
    }
}